// 表白页面交互功能 - 修复版

// 全局函数定义
window.createHeartExplosion = createHeartExplosion;
window.showHiddenMessage = showHiddenMessage;
window.showResponseModal = showResponseModal;
window.initGallery = initGallery;

document.addEventListener('DOMContentLoaded', function() {
    // 创建漂浮的心形
    createFloatingHearts();
    
    // 初始化恐龙跳一跳游戏
    initDinoGame();
    
    // 心形按钮点击事件
    const heartBtn = document.querySelector('.heart-btn');
    if (heartBtn) {
        heartBtn.addEventListener('click', function() {
            createHeartExplosion();
            showHiddenMessage();
        });
    }
    
    // 鼠标跟随心形效果
    document.addEventListener('mousemove', function(e) {
        createFollowingHeart(e.clientX, e.clientY);
    });
    
    // 打字机效果输入
    setupTypewriterEffect();
    
    // 发送按钮点击事件
    const sendBtn = document.getElementById('sendBtn');
    if (sendBtn) {
        sendBtn.addEventListener('click', sendLoveMessage);
    }
    
    // 互动选择按钮事件
    const choiceButtons = document.querySelectorAll('.choice-btn');
    choiceButtons.forEach(button => {
        button.addEventListener('click', function() {
            const response = this.getAttribute('data-response');
            showResponseModal(response);
        });
    });
    
    // 模态框关闭按钮事件
    const closeModal = document.getElementById('closeModal');
    if (closeModal) {
        closeModal.addEventListener('click', function() {
            document.getElementById('responseModal').style.display = 'none';
        });
    }
});

// 创建漂浮的心形
function createFloatingHearts() {
    const container = document.querySelector('.hearts-container');
    if (!container) return;
    
    const heartCount = 15;
    
    for (let i = 0; i < heartCount; i++) {
        const heart = document.createElement('div');
        heart.className = 'heart';
        
        // 随机位置和大小
        const size = Math.random() * 20 + 10;
        const posX = Math.random() * window.innerWidth;
        const posY = Math.random() * window.innerHeight;
        const delay = Math.random() * 5;
        const duration = Math.random() * 3 + 3;
        
        heart.style.width = `${size}px`;
        heart.style.height = `${size}px`;
        heart.style.left = `${posX}px`;
        heart.style.top = `${posY}px`;
        heart.style.animationDelay = `${delay}s`;
        heart.style.animationDuration = `${duration}s`;
        
        container.appendChild(heart);
    }
}

// 创建跟随鼠标的心形
function createFollowingHeart(x, y) {
    const container = document.querySelector('.hearts-container');
    if (!container) return;
    
    const heart = document.createElement('div');
    heart.className = 'heart following';
    
    heart.style.width = '20px';
    heart.style.height = '20px';
    heart.style.left = `${x - 10}px`;
    heart.style.top = `${y - 10}px`;
    heart.style.opacity = '0.8';
    heart.style.animation = 'none';
    
    container.appendChild(heart);
    
    // 淡出并移除心形
    setTimeout(() => {
        heart.style.transition = 'all 0.5s ease-out';
        heart.style.opacity = '0';
        heart.style.transform = 'translateY(-20px) scale(1.5)';
        
        setTimeout(() => {
            heart.remove();
        }, 500);
    }, 100);
}

// 创建心形爆炸效果
function createHeartExplosion() {
    const container = document.querySelector('.hearts-container');
    if (!container) return;
    
    const centerX = window.innerWidth / 2;
    const centerY = window.innerHeight / 2;
    const heartCount = 30;
    
    for (let i = 0; i < heartCount; i++) {
        const heart = document.createElement('div');
        heart.className = 'heart explosion';
        
        const size = Math.random() * 15 + 10;
        const angle = Math.random() * Math.PI * 2;
        const distance = Math.random() * 100 + 50;
        const duration = Math.random() * 1 + 0.5;
        
        heart.style.width = `${size}px`;
        heart.style.height = `${size}px`;
        heart.style.left = `${centerX - size/2}px`;
        heart.style.top = `${centerY - size/2}px`;
        heart.style.opacity = '1';
        heart.style.animation = 'none';
        
        // 设置爆炸动画
        setTimeout(() => {
            heart.style.transition = `all ${duration}s ease-out`;
            heart.style.transform = `translate(${Math.cos(angle) * distance}px, ${Math.sin(angle) * distance}px) rotate(${angle}rad)`;
            heart.style.opacity = '0';
        }, 10);
        
        container.appendChild(heart);
        
        // 移除心形
        setTimeout(() => {
            heart.remove();
        }, duration * 1000);
    }
}

// 显示隐藏消息
function showHiddenMessage() {
    const content = document.querySelector('.content');
    if (!content) return;
    
    const hiddenMessage = document.createElement('div');
    hiddenMessage.className = 'hidden-message';
    hiddenMessage.innerHTML = '<p>我喜欢你！</p><p>愿意和我在一起吗？</p>';
    content.appendChild(hiddenMessage);
    hiddenMessage.style.animation = 'fadeIn 1s ease-out forwards';
}

// 设置打字机效果
function setupTypewriterEffect() {
    const textarea = document.getElementById('loveInput');
    if (!textarea) return;
    
    textarea.addEventListener('input', function() {
        this.style.height = 'auto';
        this.style.height = (this.scrollHeight) + 'px';
    });
}

// 发送爱心消息
function sendLoveMessage() {
    const message = document.getElementById('loveInput')?.value.trim();
    if (!message) return;
    
    const container = document.querySelector('.hearts-container');
    const heartBtn = document.querySelector('.heart-btn');
    if (!container || !heartBtn) return;
    
    const btnRect = heartBtn.getBoundingClientRect();
    const centerX = btnRect.left + btnRect.width / 2;
    const centerY = btnRect.top + btnRect.height / 2;
    
    // 清空输入框
    document.getElementById('loveInput').value = '';
    
    // 为每个单词创建飞向心形的元素
    const words = message.split(' ');
    words.forEach((word, index) => {
        const wordElement = document.createElement('div');
        wordElement.textContent = word;
        wordElement.className = 'word-fly';
        wordElement.style.position = 'absolute';
        wordElement.style.left = `${window.innerWidth / 2}px`;
        wordElement.style.top = `${window.innerHeight / 2 + 50}px`;
        wordElement.style.color = '#ff6b81';
        wordElement.style.fontSize = '1.5rem';
        wordElement.style.fontWeight = 'bold';
        wordElement.style.opacity = '1';
        
        container.appendChild(wordElement);
        
        // 设置飞向心形的动画
        setTimeout(() => {
            wordElement.style.transition = 'all 1s ease-in-out';
            wordElement.style.transform = `translate(${centerX - window.innerWidth / 2}px, ${centerY - window.innerHeight / 2 - 50}px)`;
            wordElement.style.opacity = '0';
            
            // 动画完成后移除元素并创建心形
            setTimeout(() => {
                wordElement.remove();
                createHeartAtPosition(centerX, centerY);
            }, 1000);
        }, index * 200);
    });
}

// 在指定位置创建心形
function createHeartAtPosition(x, y) {
    const container = document.querySelector('.hearts-container');
    if (!container) return;
    
    const heart = document.createElement('div');
    heart.className = 'heart';
    heart.style.width = '30px';
    heart.style.height = '30px';
    heart.style.left = `${x - 15}px`;
    heart.style.top = `${y - 15}px`;
    heart.style.opacity = '0';
    heart.style.transform = 'scale(0)';
    
    container.appendChild(heart);
    
    // 心形出现动画
    setTimeout(() => {
        heart.style.transition = 'all 0.5s ease-out';
        heart.style.opacity = '1';
        heart.style.transform = 'scale(1.5)';
        
        // 心形消失动画
        setTimeout(() => {
            heart.style.opacity = '0';
            heart.style.transform = 'scale(0)';
            
            setTimeout(() => {
                heart.remove();
            }, 500);
        }, 1000);
    }, 10);
}

// 显示回应模态框
function showResponseModal(response) {
    const modal = document.getElementById('responseModal');
    const title = document.getElementById('modalTitle');
    const message = document.getElementById('modalMessage');
    if (!modal || !title || !message) return;
    
    if (response === 'yes') {
        title.textContent = '太棒了！';
        message.textContent = '这真是我生命中最美好的一天！让我们一起创造更多美好回忆吧！';
    } else {
        title.textContent = '我理解...';
        message.textContent = '我会一直在这里等你，直到你准备好。我的心意不会改变。';
    }
    
    modal.style.display = 'flex';
}

// 初始化画廊
function initGallery() {
    // 画廊初始化代码...
    // 这里应该包含之前gallery.js中的所有初始化逻辑
    // 由于代码较长，可以保持原gallery.js文件不变
    // 在实际项目中，可以将画廊功能保持为独立模块
}

// 添加隐藏消息的CSS（动态添加到head）
const style = document.createElement('style');
style.textContent = `
    .hidden-message {
        margin-top: 2rem;
        opacity: 0;
        transform: translateY(20px);
    }
    
    .hidden-message p {
        font-size: 1.8rem;
        margin: 1rem 0;
        text-shadow: 1px 1px 2px rgba(0,0,0,0.3);
    }
    
    .word-fly {
        z-index: 20;
    }
    
    @keyframes fadeIn {
        to {
            opacity: 1;
            transform: translateY(0);
        }
    }
`;
document.head.appendChild(style);

/* 恐龙跳一跳游戏实现 */
let gameRunning = false;
let score = 0;
let gameSpeed = 5;
let isJumping = false;
let gameInterval;

function initDinoGame() {
    const startBtn = document.getElementById('startGame');
    const dino = document.getElementById('dino');
    const obstacle = document.getElementById('obstacle');
    const scoreDisplay = document.getElementById('score');
    
    if (!startBtn || !dino || !obstacle) return;
    
    // 重置游戏状态
    function resetGame() {
        clearInterval(gameInterval);
        obstacle.style.right = '-20px';
        dino.style.transform = 'translateY(0)';
        score = 0;
        gameSpeed = 5;
        scoreDisplay.textContent = score;
        gameRunning = false;
    }
    
    // 跳跃控制
    function jump() {
        if (isJumping) return;
        
        isJumping = true;
        let jumpHeight = 0;
        let jumpUp = true;
        const jumpInterval = setInterval(() => {
            if (jumpUp) {
                jumpHeight += 5;
                dino.style.transform = `translateY(-${jumpHeight}px)`;
                if (jumpHeight >= 100) jumpUp = false;
            } else {
                jumpHeight -= 5;
                dino.style.transform = `translateY(-${jumpHeight}px)`;
                if (jumpHeight <= 0) {
                    clearInterval(jumpInterval);
                    isJumping = false;
                    dino.style.transform = 'translateY(0)';
                }
            }
        }, 20);
    }
    
    // 碰撞检测
    function checkCollision() {
        const dinoRect = dino.getBoundingClientRect();
        const obstacleRect = obstacle.getBoundingClientRect();
        
        return !(
            dinoRect.right < obstacleRect.left ||
            dinoRect.left > obstacleRect.right ||
            dinoRect.bottom < obstacleRect.top ||
            dinoRect.top > obstacleRect.bottom
        );
    }
    
    // 游戏主循环
    function gameLoop() {
        // 移动障碍物
        const obstaclePos = parseInt(obstacle.style.right || '-20px');
        obstacle.style.right = `${obstaclePos + gameSpeed}px`;
        
        // 障碍物移出屏幕后重置
        if (obstaclePos > window.innerWidth) {
            obstacle.style.right = '-20px';
            score++;
            scoreDisplay.textContent = score;
            
            // 每5分增加难度
            if (score % 5 === 0) gameSpeed += 0.5;
        }
        
        // 碰撞检测
        if (checkCollision()) {
            alert(`游戏结束！得分: ${score}`);
            resetGame();
        }
    }
    
    // 开始游戏按钮
    startBtn.addEventListener('click', function() {
        if (gameRunning) return;
        resetGame();
        gameRunning = true;
        gameInterval = setInterval(gameLoop, 20);
    });
    
    // 键盘控制
    document.addEventListener('keydown', function(e) {
        if (e.code === 'Space' && gameRunning) {
            jump();
        }
    });
    
    // 点击游戏区域也可以跳跃
    document.querySelector('.game-area').addEventListener('click', function() {
        if (gameRunning) jump();
    });
}